package com.contorller;

import com.domain.student;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class mycontroller {
    @RequestMapping(value= "frist.do")
    public ModelAndView dofrist(@RequestParam(value = "rname",required = false)String name,
                                @RequestParam(value = "rage",
                                        required = false)Integer age){
        ModelAndView mv=new ModelAndView();
        mv.addObject("myname",name);
        mv.addObject("myage",age);
        mv.addObject("mystudent",new student(name,age));
        mv.setViewName("/frist.jsp");
        return  mv;

    }
    @RequestMapping(value= "student.do")
    public String dostudent(student student,HttpServletRequest request){
        System.out.println(student);
        request.setAttribute("myname",student.getName());
        request.setAttribute("myage",student.getAge());
        request.setAttribute("mystudent",student);
        return  "/frist.jsp";
    }
    @RequestMapping(value= "void.do",method = RequestMethod.GET)
    public void dovoid(String name,int age,
                       HttpServletResponse response) throws Exception{
        student student=new student(name,age);
        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(student);
        response.getWriter().write(json);
    }
    @RequestMapping(value= "json.do",method = RequestMethod.GET)
    @ResponseBody
    public List<student> dojson(String name, int age,
                                HttpServletResponse response) throws Exception{
        student student=new student("李四",23);
        student student1=new student(name,age);
        List<student>list=new ArrayList<>();
        list.add(student);
        list.add(student1);
        return list;
    }
    @RequestMapping(value= "string.do",
            method = RequestMethod.GET,
            produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String dostring(String name, int age,
                                HttpServletResponse response) throws Exception{
        student student=new student("李四",23);
        student student1=new student(name,age);
        List<student>list=new ArrayList<>();
        list.add(student);
        list.add(student1);
        return "list";
    }
}
